﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data.SqlClient;
using System.Data;
using MySql.Data.MySqlClient;

namespace AsianSocietyPictureUpload
{
    public partial class AsianSocietyUploadPicturesToDatabase
    {
        private void FixRawGround()
        {
            if (System.IO.Directory.Exists(rawgroundPath))
            {
                string[] filePaths = Directory.GetFiles(rawgroundPath);
                for (int i = 0; i < filePaths.Length; i++)
                {
                    try
                    {

                        file = filePaths[i].ToString();
                        fileName = System.IO.Path.GetFileName(filePaths[i].ToString());

                        //Image rawImage;

                        //rawImage = CropImageFromRawGround(file);
                        //rawImage = ResizeImage(rawImage);
                        //rawImage = SaveImageToLocalFolderGroundFromRaw(rawImage, fileName);
                        //rawImage.Dispose();
                        //rawImage = null;

                        string[] Nameindex = fileName.Split('_', '.');
                        string City = Nameindex[0];
                        int CityID = GetCityGroundID(City);

                     
                    string day;

                    day = Nameindex[3];

                    if (Nameindex[3].Length > 2)
                       day = Nameindex[3].Substring(0, (Nameindex[3].Length - 1));

                        string Date = Nameindex[1]+ '-' + Nameindex[2] + '-'+ day;

                        InsertRawGroundToDatabase(CityID, fileName, Date);

                        //File.Delete(file);

                    }
                    catch { }
                }
            }
        }

        private int GetCityGroundID(string City)
        
        {
            switch (City)
            {
                case "Beijing":
                    return 3;
                case "NYC":
                    return 7;
                case "Chicago":
                    return 11;
                case "Guangzhou":
                    return 4;
                case "HK":
                    return 6;
                case "Phoenix":
                    return 8;
                case "Shanghai":
                    return 5;
                default:
                    return 0;
            }
        }

        private DateTime GetDate(string year,string month,string day)
        {
            DateTime newDate = new DateTime(Convert.ToInt32(year),Convert.ToInt32(month),Convert.ToInt32(day));
            return newDate;
        }

        private void InsertRawGroundToDatabase(int CityID, string filePath, string date)
        {
            MySqlConnection mySQLCon = new MySqlConnection(setString.chinaairConnectionString);
            string sqlComand = "select mid from chinaair.tb_city_pollution where fcityid =" + CityID + " and zdate = '" + date + "'";

            mySQLCon.Open();

            MySqlCommand checkMID = new MySql.Data.MySqlClient.MySqlCommand(sqlComand, mySQLCon);

            MySqlDataReader dr = checkMID.ExecuteReader();


            int MID = 0;


            while (dr.Read())
            {
                MID = Convert.ToInt32(dr["mid"]);
            }

            dr.Close();

            if (MID > 0)
            {
                MySql.Data.MySqlClient.MySqlCommand updateMainImage = new MySql.Data.MySqlClient.MySqlCommand("UPDATE chinaair.tb_city_pollution  SET  mainimg1 = 'display/ground/" + filePath + "', zenable = 'Y' WHERE  (fcityid =" + CityID + ") AND (zdate = '" + date + "')");

                updateMainImage.Connection = mySQLCon;
                updateMainImage.ExecuteNonQuery();
            }
            else
            {

                AsiaDBTableAdapters.tb_city_pollutionTableAdapter cityPolluA = new AsiaDBTableAdapters.tb_city_pollutionTableAdapter();

                cityPolluA.Insert("Y",
                                    Convert.ToDateTime(date),
                                    CityID,
                                    "0",
                                    "0",
                                    "0",
                                    "0",
                                    "0",
                                    "0",
                                    "display/ground/" + filePath,
                                    "",
                                    "",
                                    3,
                                    1,
                                    DateTime.Now.Date,
                                    5,
                                    DateTime.Now.Date,
                                    0,
                                    0);
            }
            mySQLCon.Close();
        }

        private Image CropImageFromRawGround(string rawImagePath)
        {
            
            Bitmap bmpImage = new Bitmap(rawImagePath);

            double oldMargin = bmpImage.Height/(double)bmpImage.Width;
            double wantedMargin = 632/(double)980;
            double newMargin;

            if (oldMargin > wantedMargin)
            {
                newMargin = oldMargin - wantedMargin;
            }
            else
            {
                newMargin = wantedMargin - oldMargin;
            }

            int x = Convert.ToInt32(bmpImage.Width);
            int y = Convert.ToInt32(bmpImage.Height * (1 - newMargin));

            Rectangle cropArea = new Rectangle(0, 0, x, y);

            Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
            bmpImage.Dispose();
            bmpCrop.SetResolution(72.0F, 72.0F);

            return (Image)bmpCrop;
        }

        private Image SaveImageToLocalFolderGroundFromRaw(Image rawImage, string NewfileName)
        {
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

            EncoderParameters myEncoderParameters = new EncoderParameters(1);

            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 90L);
            myEncoderParameters.Param[0] = myEncoderParameter;


            if (rawImage != null)
                rawImage.Save(groundPath + NewfileName, jgpEncoder, myEncoderParameters);

            return rawImage;
        }
    }
}
